﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Text;

public partial class userManager : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e) {
        if (!IsPostBack) {
            CSUtils.CheckSession();
            this.binddata();
            this.initTree();
            PanelInput.Visible = false;
        }

    }

    protected void ButtonQuery_Click(object sender, EventArgs e)
    {
        binddata();
    }

    private void binddata() {
        GridView1.DataSource = this.getAllUser();
        GridView1.DataBind();
    }

    private DataSet getAllUser()
    {
        string sql =
            "select *, case user_type when 1 then '后台管理' when 2 then '销售代表' end as user_type_name, " +
            "  case user_market_type when 0 then '全部' when 1 then '内销' when 2 then '外销' when 3 then '门市' when 4 then '零配' end as market_type_name " +  
            "from cs_users " +
            "where {0} " +
            "order by user_name";

        string where = "visible = 1 and user_type != 9 ";

        string userCode = TextBoxUserCode.Text;
        if (userCode.Trim() != "")
        {
            where += "and user_code ='" + userCode + "' ";
        }

        string userName = TextBoxUserName.Text;
        if (userName.Trim() != "")
        {
            where += "and user_name like '%" + userName + "%' ";
        }

        sql = string.Format(sql, where);


        DataSet ds = new DataSet();
        DBConn myDB = new DBConn();
        ds = myDB.getDataSet(sql);
        myDB.Close();
        return ds;
    }

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) {
        GridView1.PageIndex = e.NewPageIndex;
        this.binddata();
    }


    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) {
        
        if (e.CommandName.Equals("command_edit") ||
            e.CommandName.Equals("command_add")) {

            PanelInput.Visible = true;
            TextBoxCommandType.Text = e.CommandName;
            LabelID.Text = e.CommandArgument.ToString();
            UserVO vo = CSUtils.getUser(LabelID.Text);
            LabelUserCode.Text = vo.Code;
            TextBoxName.Text = vo.Name;
            DropDownListType.SelectedValue = vo.Type;
            DropDownListMarketType.SelectedValue = vo.MarketType;
            TextBoxPassword.Text = vo.Password;
            this.setInputDegrees(vo.UserDegrees);

            //string userPower = "a,a01,a02,d,e,e03,e11,a03,a04,a05,a06,a07,a08,a09,a10,a11,a12,a13,a14,a15,b,b01,b02,b03,b04,b05,b06,b07,b08,b09,b10,b11,b12,b13,c,c01,c02,c03,c04,c05,c06,c07,d01,d02,d03,e01,e02,e04,e05,e06,e07,e08,e09,e10,e12,e13,e14,e15,e16,e17,f,f01,f02,f03,f04,g,g01,g02,g03,g04,g05,g06,g07,g08,g09,h,h01,h02,h03,h04,h05,h06,h07,i,i01,i02,i03,i04,j,j01,j02,j03,j04,j05,j06,k,k01,k02,k03,k04,k05,k06,";
            string userMenus = vo.UserMenus;
            string[] tmp = userMenus.Split(',');
            ArrayList values = new ArrayList();
            for (int i = 0, n = tmp.Length; i < n; i++)
            {
                if (tmp[i] != "")
                {
                    values.Add(tmp[i]);
                }
            }
            this.setNode(TreeView1.Nodes, values);

        }
        else if (e.CommandName.Equals("command_del"))
        {
            string userID = e.CommandArgument.ToString();
            UserVO user = CSUtils.getUser(userID);
            if (user.Type == "2")
            {
                JScript.Alert("销售代表不能删除！");
                return;
            }

            if (this.delUser(userID))
            {
            }
            else
            {
                JScript.Alert("删除失败！");
            }

            this.binddata();
            this.cleanPanelInput();
        }
        else if (e.CommandName.Equals("command_allow"))
        {
            string userID = e.CommandArgument.ToString();

            if (this.updateAllowLogin(userID))
            {

            }
            else
            {
                JScript.Alert("保存失败！");
            }

            this.binddata();
        }
        else
        {
            this.cleanPanelInput();
        }               

    }


    protected void ButtonSubmit_Click(object sender, EventArgs e) {

        string userID = LabelID.Text;
        string userName = TextBoxName.Text;
        string userType = DropDownListType.SelectedValue;
        string userPassword = TextBoxPassword.Text;
        string userDegrees = this.getInputDegrees();
        string marketType = DropDownListMarketType.SelectedValue;

        StringBuilder checkeddMenus = new StringBuilder();
        TreeNodeCollection checkedNodes = TreeView1.CheckedNodes;
        foreach (TreeNode t in checkedNodes)
        {
            checkeddMenus.Append(t.Value + ",");
        }

        string commandType = TextBoxCommandType.Text;
        UserVO vo = null;
        if (commandType.Equals("command_edit"))
        {
            //get vo from db
            vo = CSUtils.getUser(userID);

            //update there info
            vo.Name = userName;
            vo.Type = userType;
            vo.Password = userPassword;
            vo.UserDegrees = userDegrees;
            vo.UserMenus = checkeddMenus.ToString();
            vo.MarketType = marketType;
        }
        else if (commandType.Equals("command_add"))
        {
            vo = new UserVO();
            vo.Code = this.getMaxUserCode();
            vo.Name = userName;
            vo.Type = userType;
            vo.Password = userPassword;
            vo.UserDegrees = userDegrees;
            vo.UserMenus = checkeddMenus.ToString();
            vo.MarketType = marketType;
        }

        if (CSUtils.mergeUser(vo))
        {
            //JScript.Alert("保存成功！");
        }
        else
        {
            JScript.Alert("保存失败！");
        }

        this.binddata();

    }

    protected void LinkButtonAdd_Click(object sender, EventArgs e) {
        PanelInput.Visible = true;
        TextBoxCommandType.Text = "command_add";
        this.cleanPanelInput();

    }



    private void cleanPanelInput() {

        LabelID.Text = "";
        LabelUserCode.Text = "系统稍候生成";
        TextBoxName.Text = "";
        TextBoxPassword.Text = "";
        DropDownListType.SelectedIndex = 0;
        this.setNode(TreeView1.Nodes, new ArrayList());
    }


    private string getMaxUserCode()
    {
        string maxNumber = "";
        string sql =
            "select isnull(max(convert(int,user_code)),0)+1 as maxNumber from cs_users where user_code <> 'gwang'";

        DBConn myDB = new DBConn();
        SqlDataReader dr = myDB.getDataReader(sql);
        if (dr.Read())
        {
            maxNumber = dr["maxNumber"].ToString();
        }
        dr.Close();
        myDB.Close();

        if (maxNumber.Length == 1)
        {
            maxNumber = "0000" + maxNumber;
        }
        else if (maxNumber.Length == 2)
        {
            maxNumber = "000" + maxNumber;
        }
        else if (maxNumber.Length == 3)
        {
            maxNumber = "00" + maxNumber;
        }
        else if (maxNumber.Length == 4)
        {
            maxNumber = "0" + maxNumber;
        }
        else if (maxNumber.Length == 5)
        {
            ;
        }

        return maxNumber;

    }

    private bool delUser(string userID)
    {
        string sql =
            "update cs_users set visible = 0 where user_id = {0}";

        sql = string.Format(sql, userID);
        DBConn myDB = new DBConn();
        int ret = myDB.Update(sql);
        myDB.Close();
        return ret > 0;
    }

    private string getInputDegrees()
    {
        string degrees = "";
        if (CheckBoxDegree1.Checked)
        {
            degrees += "1";
        }
        return degrees;
    }

    private void setInputDegrees(string degrees)
    {
        if (degrees == null)
        {
            degrees = "";
        }

        if (degrees.IndexOf("1") > -1)
        {
            CheckBoxDegree1.Checked = true;
        }
        else
        {
            CheckBoxDegree1.Checked = false;
        }

    }

    private bool updateAllowLogin(string userID)
    {

        string sqlUpdate =
            "update cs_users " +
            "set allow_login = allow_login-1 " +
            "where user_id = " + userID;

        DBConn myDB = new DBConn();
        int tmp = myDB.Update(sqlUpdate);
        myDB.Close();
        return (tmp == 1);

    }

    protected void initTree()
    {
        TreeView1.Nodes.Clear();
        createChildTree("cs_menus", TreeView1, null, "0");

        //绑定事件
        TreeView1.Attributes.Add("onclick", "treeNodeClick()");

    }

    protected void createChildTree(string tableName, TreeView treeName, TreeNode parentNode, string parentCode)
    {
        string sql =
            "select * " +
            "from " + tableName + " " + 
            "where parent_code = '" + parentCode + "' " +
            "order by disp_order";

        DBConn myDB = new DBConn();
        SqlDataReader dr = myDB.getDataReader(sql);
        while (dr.Read())
        {
            TreeNode node = new TreeNode(dr["menu_name"].ToString(), dr["menu_code"].ToString());
            node.SelectAction = TreeNodeSelectAction.None;      //不生成link
            createChildTree(tableName, treeName, node, dr["menu_code"].ToString());  //递归出子节点
            if (parentNode == null)
            {
                treeName.Nodes.Add(node);
            }
            else
            {
                parentNode.ChildNodes.Add(node);
            }

        }
        dr.Close();
        myDB.Close();
    }

    private void setNode(TreeNodeCollection tc, ArrayList values)
    {
        foreach (TreeNode node in tc)
        {
            if (values.Contains(node.Value))
            {
                node.Checked = true;
                values.Remove(node.Value);
            }
            else
            {
                node.Checked = false;
            }
            setNode(node.ChildNodes, values);           //递归设置子节点
        }
    }
    
}
